//本代码用来测试子进程提供匿名管道将信息传递给父进程 24/11/5
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define SIZE 1024

void writer(int wfd)
{
    char buf[SIZE];
    const char* str = "hello father,i am child";
    int count = 1;
    pid_t id = getpid();
    while(true)
    {
        //格式化输入
        snprintf(buf,sizeof(buf)-1,"message:%s,pid:%d,times:%d\n",str,id,count);
        write(wfd,buf,strlen(buf));
        count+=1;
        sleep(1);

    }
}

void reader(int rfd)
{
    char buf[SIZE];
    while(true)
    {
        ssize_t n = read(rfd,buf,sizeof(buf)-1);
        if(n == -1)
        {
            perror("read");
            return;
        }
        printf("%s",buf);
    }

}

int main()
{
    //文件标识符
    int fd[2];
    if(pipe(fd) < 0)
    {
        //error
        perror("pipe error");
        return 1;
    }
    pid_t id = fork();
    if(id<0)
    {
        perror("fork error");
        return 1;
    }
    else if(id == 0)
    {
        //child
        //关闭读端
        close(fd[0]);
        writer(fd[1]);
        exit(1);
    }
    //father
    close(fd[1]);
    reader(fd[0]);
    wait(NULL);
    return 0;
}
